(function (window, angular) {
    'use strict';
    angular.module("Controller.Maintenance.MarketingCenterArea", [])
        .controller("MarketingCenterAreaCtrl", ["$scope", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", function ($scope, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout) {
            $scope.activeFlag = [true, false];
            $scope.markInfo = {
                curRow: 0
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };

            $scope.condition = {};
            $scope.dataList = [];

            $scope.tableConfig = {
                fixedWidth: 80,
                scrollWidth: 1200,
                tableCol: [
                    {
                        name: "销售服务中心名称",
                        dataField: "mc",
                        width: 300,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "销售服务中心代码",
                        dataField: "dm",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "电话",
                        dataField: "dh",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "用途对象",
                        dataField: "useObj",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "省市代码",
                        dataField: "ssdm",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "地址",
                        dataField: "dz",
                        width: 440,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "操作",
                        isShow: true,
                        isFixed: true,
                    }
                ]
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            function getDataList(curPage) {
                var service = "sync";
                var reqUrl = "/ynMarketingCenter/list";
                var param = {};
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageSize = $scope.pageInfo.pageSize;
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {scrollLeft: {left: $scope.tableConfig.fixedWidth + "px"}};
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show"+ toolbar]) {
                    $scope.toolbarConfig["show"+ toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show"+ toolbar] = true;
                    });
                }
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            // 获取全中国省市信息
            $scope.proCityDatas = [];
            $timeout(function () {
                const districtSearch = new AMap.DistrictSearch({
                    level: 'country',
                    subdistrict: 3
                })
                districtSearch.search('中国', (status, result) => {
                    if (status == 'complete' && result.info === 'OK') {
                        $scope.proCityDatas = result.districtList[0].districtList
                    }
                })
            });

            // 初始化省市选中状态
            function initProCityDatasStatus (source) {
                angular.forEach(source, function(item) {
                    item.isChecked = false
                    if (item.districtList && item.districtList.length > 0) {
                        initProCityDatasStatus(item.districtList)
                    }
                })
            }

            // 根据已选择的省市信息 处理省市选中状态
            function handleProCityDatasStatus (source, targetData, parent) {
                angular.forEach(source, function(item) {
                    if (item.level == 'province') {
                        if (item.districtList && item.districtList.length > 0) {
                            handleProCityDatasStatus(item.districtList, targetData, item)
                        } else {
                            // 没有市的省
                            if (targetData.map(t => t.province).includes(item.name)) {
                                item.isChecked = true
                            } else {
                                item.isChecked = false
                            }
                        }
                    } else if (item.level == 'city') {
                        if (targetData.map(t => t.city).includes(item.name)) {
                            item.isChecked = true
                        } else {
                            item.isChecked = false
                        }
                        checkProvinceStatus(parent)
                    }
                })
            }

            $scope.bindProCityList = [];
            $scope.getBindProCitys = function (item) {
                initProCityDatasStatus($scope.proCityDatas)

                $scope.curMarketingCenter = {
                    mc: item.mc,
                    dm: item.dm,
                    guid: item.guid,
                    dh: item.dh,
                    ssdm: item.ssdm,
                    ytdx: item.ytdx,
                    dz: item.dz,
                    zb: item.zb,
                    jl: item.jl,
                    jlsj: item.jlsj,
                };
                ybHttp.Post('mt', '/marketingCenterArea/list', { filters: { guid: item.guid } }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error)
                        return;
                    }
                    $scope.bindProCityList = resp.value.list || []
                    handleProCityDatasStatus($scope.proCityDatas, $scope.bindProCityList)
                    $scope.changeTab(1)
                });
            };

            // 删除选择的省市
            $scope.delProcity = function (index, needCheckProvince) {
                $scope.bindProCityList.splice(index, 1);
                if (needCheckProvince) {
                    handleProCityDatasStatus($scope.proCityDatas, $scope.bindProCityList)
                }
            };

            // 选择省
            $scope.selectProvince = function (province) {
                if (!province.isChecked) {
                    if (province.districtList && province.districtList.length > 0) {
                        angular.forEach(province.districtList, function(city) {
                            city.isChecked = false
                            const findIdx = $scope.bindProCityList.findIndex(b => b.city == city.name)
                            if (findIdx != -1) {
                                $scope.delProcity(findIdx)
                            }
                        })
                    } else {
                        // 没有市的省
                        $scope.delProcity($scope.bindProCityList.findIndex(b => b.province == province.name))
                    }
                } else {
                    if (province.districtList && province.districtList.length > 0) {
                        angular.forEach(province.districtList, function(city) {
                            if (!city.isChecked) {
                                city.isChecked = true
                                $scope.bindProCityList.push({
                                    mc: $scope.curMarketingCenter.mc,
                                    province: province.name,
                                    city: city.name,
                                })
                            }
                        })
                    } else {
                        // 没有市的省
                        $scope.bindProCityList.push({
                            mc: $scope.curMarketingCenter.mc,
                            province: province.name,
                        })
                    }
                }

            };

            // 选择市
            $scope.selectCity = function (province, city) {
                checkProvinceStatus(province)
                if (!city.isChecked) {
                    $scope.delProcity($scope.bindProCityList.findIndex(b => b.city == city.name))
                } else {
                    $scope.bindProCityList.push({
                        mc: $scope.curMarketingCenter.mc,
                        province: province.name,
                        city: city.name,
                    })
                }
            };

            function checkProvinceStatus(pro) {
                let uncheckedNum = 0;
                const list = pro.districtList || []
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        uncheckedNum ++
                    }
                }
                if (uncheckedNum == 0) {
                    pro.isChecked = true
                } else if (uncheckedNum == list.length) {
                    pro.isChecked = false
                } else {
                    pro.isChecked = 'notAll'
                }
            }

            // 销售服务中心 绑定 省市
            $scope.saveData =function () {
                const params = angular.extend({areaVOList:$scope.bindProCityList}, $scope.curMarketingCenter)
                ybHttp.Post('mt', '/marketingCenterArea/insert', params).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };

            (function () {
                getDataList();
                $scope.setFixedWidth();
            })();
        }])
    ;
})(window, window.angular);